<template>
  <div class="course-detail" v-loading="loading" element-loading-text="加载中...">
    <!-- 课程标题与进度 -->
    <el-card shadow="never" class="course-header">
      <div class="header-content">
        <div class="header-left">
          <div class="title-row">
            <el-button 
              icon="el-icon-arrow-left" 
              circle 
              size="small"
              @click="$router.back()"
            ></el-button>
            <h1 class="course-title">{{ course.name }}</h1>
          </div>
          <p class="course-meta">课程分类: {{ course.type }}</p>
        </div>
        
        <div class="header-right">
          <div class="progress-info">
            <div class="progress-header">
              <span>总体进度</span>
              <span class="progress-value">{{ course.progress }}%</span>
            </div>
            <el-progress 
              :percentage="course.progress" 
              :stroke-width="8"
            ></el-progress>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 课程内容标签页 -->
    <div class="tabs-container">
      <div class="tabs-header">
        <button 
          :class="['tab-button', { active: activeTab === 'content' }]"
          @click="activeTab = 'content'"
        >
          课程内容
        </button>
      </div>
    </div>

    <!-- 知识学习部分 -->
    <el-card shadow="never" class="content-section">
      <div slot="header" class="section-header">
        <div class="section-title">
          <i class="el-icon-notebook-2"></i>
          <span>知识学习</span>
        </div>
        <span class="section-stats">{{ completedLearning }}/{{ totalLearning }} 已完成</span>
      </div>

      <div class="chapters-list">
        <div 
          v-for="chapter in chapters" 
          :key="chapter.id"
          class="chapter-item"
        >
          <div 
            class="chapter-header"
            @click="toggleChapter(chapter.id)"
          >
            <span class="chapter-title">{{ chapter.title }}</span>
            <i 
              :class="['el-icon-arrow-down', 'chapter-icon', { collapsed: !chapter.expanded }]"
            ></i>
          </div>

          <transition name="el-zoom-in-top">
            <div v-show="chapter.expanded" class="chapter-content">
              <div 
                v-for="item in chapter.items" 
                :key="item.id"
                class="learning-item"
              >
                <div class="item-icon">
                  <i 
                    :class="item.completed ? 'el-icon-success' : 'el-icon-circle-close'"
                    :style="{ color: item.completed ? '#00B42A' : '#C9CDD4' }"
                  ></i>
                </div>
                
                <div class="item-info">
                  <div class="item-title-row">
                    <span class="item-title">{{ item.title }}</span>
                    <el-tag :type="getTypeTagType(item.type)" size="mini">
                      {{ item.type }}
                    </el-tag>
                  </div>
                  <p class="item-meta">{{ item.duration }} | {{ item.description }}</p>
                </div>

                <el-button 
                  type="text" 
                  @click="openLearningContent(item)"
                >
                  {{ item.completed ? '已学习' : '学习' }}
                </el-button>
              </div>
            </div>
          </transition>
        </div>
      </div>
    </el-card>

    <!-- 测验部分 -->
    <el-card shadow="never" class="content-section">
      <div slot="header" class="section-header">
        <div class="section-title">
          <i class="el-icon-edit-outline"></i>
          <span>章节测验</span>
        </div>
        <span class="section-stats">{{ completedQuizzes }}/{{ quizzes.length }} 已完成</span>
      </div>

      <div class="quizzes-list">
        <div 
          v-for="quiz in quizzes" 
          :key="quiz.id"
          class="quiz-item"
        >
          <div class="quiz-info">
            <div class="quiz-title">{{ quiz.title }}</div>
            <p class="quiz-meta">{{ quiz.questionCount }}题 | 单选+多选</p>
          </div>

          <div class="quiz-result">
            <span :class="['quiz-score', { completed: quiz.score !== null }]">
              {{ quiz.score !== null ? quiz.score + '分' : '-' }}
            </span>
            <p class="quiz-status">{{ quiz.score !== null ? '已完成' : '未完成' }}</p>
          </div>

          <el-button 
            :type="quiz.score !== null ? 'default' : 'primary'"
            @click="handleQuizAction(quiz)"
          >
            {{ getQuizButtonText(quiz) }}
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 学习内容弹窗 -->
    <el-dialog
      :title="learningDialog.title"
      :visible.sync="learningDialog.visible"
      :width="learningDialogWidth"
      :top="learningDialogTop"
      :close-on-click-modal="false"
      :fullscreen="isMobile"
      custom-class="learning-dialog"
    >
      <div class="learning-content">
        <div v-if="learningDialog.type === '视频'" class="video-container">
          <video controls class="learning-video">
            <source :src="learningDialog.url" type="video/mp4">
            您的浏览器不支持视频播放
          </video>
          <p class="content-desc">本视频讲解了{{ learningDialog.title }}的基本概念和原理,帮助您理解相关知识。</p>
        </div>

        <div v-else-if="learningDialog.type === 'PDF'" class="pdf-container">
          <div v-if="learningDialog.pdfUrls && learningDialog.pdfUrls.length > 0" class="pdf-viewer">
            <!-- 当前PDF展示 -->
            <iframe 
              :src="learningDialog.pdfUrls[learningDialog.currentPdfIndex]" 
              class="pdf-iframe"
              :class="{ 'pdf-iframe-multiple': learningDialog.pdfUrls.length > 1 }"
            ></iframe>
            
            <!-- PDF 分页控制 -->
            <div v-if="learningDialog.pdfUrls.length > 1" class="pdf-pagination">
              <el-button 
                icon="el-icon-arrow-left" 
                :disabled="learningDialog.currentPdfIndex === 0"
                @click="prevPdf"
                size="small"
              >
                上一页
              </el-button>
              <span class="pdf-page-info">
                {{ learningDialog.currentPdfIndex + 1 }} / {{ learningDialog.pdfUrls.length }}
              </span>
              <el-button 
                icon="el-icon-arrow-right" 
                :disabled="learningDialog.currentPdfIndex === learningDialog.pdfUrls.length - 1"
                @click="nextPdf"
                size="small"
              >
                下一页
              </el-button>
            </div>
          </div>
          <div v-else class="pdf-placeholder">
            <i class="el-icon-document" style="font-size: 64px; color: #F53F3F"></i>
            <p class="pdf-title">{{ learningDialog.title }}</p>
            <p class="content-desc">PDF文件加载中...</p>
          </div>
        </div>

        <div v-else-if="learningDialog.type === '网页'" class="webpage-container">
          <iframe :src="learningDialog.url" class="learning-iframe"></iframe>
          <p class="content-desc">这是来自外部网站的参考资料,介绍了{{ learningDialog.title }}的相关内容。</p>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="learningDialog.visible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 测验结果弹窗 -->
    <el-dialog
      title="测验结果"
      :visible.sync="quizResultDialog.visible"
      :width="quizDialogWidth"
      top="5vh"
      :fullscreen="isMobile"
      custom-class="quiz-result-dialog"
    >
      <div class="quiz-result-content">
        <div class="result-summary">
          <div class="score-circle">
            <span class="score-number">{{ parseFloat(quizResultDialog.score) }}</span>
            <span class="score-unit">分</span>
          </div>
          <p class="result-message">恭喜您通过了本章测验</p>
        </div>

        <div class="result-stats">
          <div class="stat-row">
            <span class="stat-label">总题数</span>
            <span class="stat-value">{{ quizResultDialog.totalQuestions }}题</span>
          </div>
          <div class="stat-row">
            <span class="stat-label">做对题数</span>
            <span class="stat-value" style="color: #00B42A">{{ quizResultDialog.correctCount }}题</span>
          </div>
          <div class="stat-row">
            <span class="stat-label">正确率</span>
            <span class="stat-value">{{ quizResultDialog.accuracy }}%</span>
          </div>
        </div>

        <div v-if="quizResultDialog.wrongQuestions.length > 0" class="wrong-questions">
          <div class="wrong-header">错题回顾</div>
          <div 
            v-for="(question, index) in quizResultDialog.wrongQuestions" 
            :key="index"
            class="wrong-item"
          >
            <p class="question-text">{{ question.id }}. {{ question.text }}</p>
            <div class="options-list">
              <div 
                v-for="option in question.options" 
                :key="option.key"
                :class="['option-item', getOptionClass(option, question)]"
              >
                <span class="option-key">{{ option.key }}</span>
                <span class="option-text">{{ option.text }}</span>
                <el-tag 
                  v-if="option.key === question.userAnswer" 
                  size="mini" 
                  type="danger"
                >
                  您的答案
                </el-tag>
                <el-tag 
                  v-if="option.key === question.correctAnswer" 
                  size="mini" 
                  type="success"
                >
                  正确答案
                </el-tag>
              </div>
            </div>
            <div class="answer-explanation">
              <p class="explanation-title">答案解释:</p>
              <p class="explanation-text">{{ question.explanation }}</p>
            </div>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="quizResultDialog.visible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CourseDetail',
  data() {
    return {
      activeTab: 'content',
      windowWidth: window.innerWidth,
      loading: false,
      courseId: null,
      course: {
        name: '',
        number: '',
        type: '',
        progress: 0
      },
      chapters: [],
      quizzes: [],
      learningDialog: {
        visible: false,
        title: '',
        type: '',
        url: '',
        pdfUrls: [],
        currentPdfIndex: 0,
        currentItem: null
      },
      quizResultDialog: {
        visible: false,
        score: 85,
        totalQuestions: 10,
        correctCount: 8,
        accuracy: 80,
        wrongQuestions: [
          {
            id: 3,
            text: '下列哪种不是焊接接头的基本形式?',
            options: [
              { key: 'A', text: '对接接头' },
              { key: 'B', text: '角接接头' },
              { key: 'C', text: '搭接接头' },
              { key: 'D', text: '嵌套接头' }
            ],
            userAnswer: 'C',
            correctAnswer: 'D',
            explanation: '焊接接头的基本形式包括对接接头、角接接头、搭接接头和T形接头。这些接头形式是根据被焊接工件的相对位置和连接方式来划分的。嵌套接头不属于基本焊接接头形式,它通常用于特定的管道连接或特殊结构中,需要配合其他连接方式使用。'
          },
          {
            id: 7,
            text: '下列哪种因素不会导致焊接气孔的产生?',
            options: [
              { key: 'A', text: '焊接材料受潮' },
              { key: 'B', text: '保护气体流量不足' },
              { key: 'C', text: '焊接速度过快' },
              { key: 'D', text: '焊接电流稳定' }
            ],
            userAnswer: 'A',
            correctAnswer: 'D',
            explanation: '焊接气孔产生的主要原因包括:焊接材料受潮导致水分蒸发产生气体、保护气体流量不足无法有效隔绝空气、焊接速度过快导致气体来不及逸出等。而稳定的焊接电流是保证焊接质量的重要条件,不会直接导致气孔产生。相反,电流不稳定可能会引起熔池波动,间接增加气孔产生的可能性。'
          }
        ]
      }
    }
  },
  computed: {
    totalLearning() {
      return this.chapters.reduce((sum, chapter) => sum + chapter.items.length, 0)
    },
    completedLearning() {
      return this.chapters.reduce((sum, chapter) => {
        return sum + chapter.items.filter(item => item.completed).length
      }, 0)
    },
    completedQuizzes() {
      return this.quizzes.filter(q => q.score !== null).length
    },
    isMobile() {
      return this.windowWidth <= 768
    },
    learningDialogWidth() {
      if (this.windowWidth <= 768) {
        return '100%'
      } else if (this.windowWidth <= 1024) {
        return '95%'
      } else if (this.windowWidth <= 1440) {
        return '90%'
      } else {
        return '1400px'
      }
    },
    learningDialogTop() {
      // PDF类型需要更大的展示空间
      if (this.learningDialog.type === 'PDF') {
        return '3vh'
      }
      return '5vh'
    },
    quizDialogWidth() {
      if (this.windowWidth <= 768) {
        return '100%'
      } else if (this.windowWidth <= 1024) {
        return '90%'
      } else {
        return '700px'
      }
    }
  },
  mounted() {
    this.courseId = this.$route.params.id
    this.getCourseDetail()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    // 获取课程详情
    async getCourseDetail() {
      if (!this.courseId) {
        this.$message.error('课程ID无效')
        return
      }
      
      this.loading = true
      try {
        const res = await this.$api.course.getCourseDetail({
          course_id: this.courseId
        })
        
        // 后端返回结构: { course_info, knowledge_list, paper_list }
        
        // 处理课程基本信息
        if (res.course_info) {
          const courseInfo = res.course_info
          this.course = {
            name: courseInfo.name || '',
            number: courseInfo.code || '',
            type: courseInfo.category?.name || '理论课程',
            progress: 0 // 会在处理完知识点后计算
          }
        }
        
        // 统计知识点学习情况
        let totalCount = 0
        let completedCount = 0
        
        // 处理学习内容(知识点) - 后端返回 knowledge_list
        if (res.knowledge_list && res.knowledge_list.length > 0) {
          // 按分类分组知识点
          const knowledgeMap = {}
          
          res.knowledge_list.forEach((knowledge, index) => {
            const categoryName = knowledge.category?.name || knowledge?.title || '未分类'
            if (!knowledgeMap[categoryName]) {
              knowledgeMap[categoryName] = []
            }
            
            const isCompleted = knowledge.learned_status === 1
            totalCount++
            if (isCompleted) completedCount++
            
            knowledgeMap[categoryName].push({
              id: knowledge.id,
              title: knowledge.title,
              type: this.mapKnowledgeType(knowledge.type),
              duration: knowledge.duration || '30分钟',
              description: knowledge.description || '',
              completed: isCompleted, // 后端返回 learned_status
              url: knowledge.file_url || knowledge.third_party_link || ''
            })
          })
          
          // 转换为章节格式
          this.chapters = Object.keys(knowledgeMap).map((categoryName, index) => ({
            id: index + 1,
            title: `${index + 1}. ${categoryName}`,
            expanded: index === 0,
            items: knowledgeMap[categoryName]
          }))
          
          // 计算总体进度（知识点完成率）
          this.course.progress = totalCount > 0 ? Math.round((completedCount / totalCount) * 100) : 0
        }
        
        // 处理测验考试 - 后端返回 paper_list
        if (res.paper_list && res.paper_list.length > 0) {
          this.quizzes = res.paper_list.map(paper => ({
            id: paper.id,
            title: paper.name,
            questionCount: paper.question_count || 0,
            score: paper.score || null, // 后端返回 score 字段
            // 测验随时可用
            enabled: true
          }))
        }
      } catch (error) {
        this.$message.error('获取课程详情失败')
      } finally {
        this.loading = false
      }
    },
    
    // 映射知识类型
    mapKnowledgeType(type) {
      const typeMap = {
        1: 'PDF',
        2: '视频',
        3: '网页'
      }
      return typeMap[type] || 'PDF'
    },
    
    // 获取知识点时长
    getKnowledgeDuration(knowledge) {
      if (knowledge.type === 1) {
        return `${knowledge.page_count || 0}页`
      } else if (knowledge.type === 2) {
        return `${knowledge.duration || 0}分钟`
      } else {
        return '外部资源'
      }
    },
    
    handleResize() {
      this.windowWidth = window.innerWidth
    },
    toggleChapter(chapterId) {
      const chapter = this.chapters.find(c => c.id === chapterId)
      if (chapter) {
        chapter.expanded = !chapter.expanded
      }
    },
    getTypeTagType(type) {
      const typeMap = {
        '视频': 'primary',
        'PDF': 'danger',
        '网页': 'success'
      }
      return typeMap[type] || ''
    },
    async openLearningContent(item) {

      // 如果未学习，先调用标记为已学习接口
      if (!item.completed) {
        try {
          await this.$api.knowledge.markKnowledgeLearned({
            course_id: this.courseId,
            knowledge_id: item.id
          })
          
          item.completed = true
          this.$message.success('已标记为已学习')
          
          // 重新计算进度
          this.updateProgress()
        } catch (error) {
          this.$message.error('标记失败')
          return
        }
      }

      // 统一处理 URL
      let url = item.url
      let pdfUrls = []
      
      // 对于 PDF 类型，解析 JSON 字符串获取 URL 数组
      if (item.type === 'PDF') {
        try {
          const parsed = JSON.parse(item.url)
          if (Array.isArray(parsed)) {
            pdfUrls = parsed
            url = parsed[0] // 保留第一个作为默认URL
          } else {
            pdfUrls = [item.url]
            url = item.url
          }
        } catch(e) {
          // 如果不是JSON，尝试作为单个URL
          pdfUrls = [item.url]
          url = item.url
        }
      } else {
        // 对于非 PDF 类型，尝试解析 JSON 字符串
        try {
          url = JSON.parse(item.url)
        } catch(e) {
          url = item.url
        }
      }

      this.learningDialog = {
        visible: true,
        title: item.title,
        type: item.type,
        url: url,
        pdfUrls: pdfUrls,
        currentPdfIndex: 0,
        currentItem: item
      }
    },
    prevPdf() {
      if (this.learningDialog.currentPdfIndex > 0) {
        this.learningDialog.currentPdfIndex--
      }
    },
    nextPdf() {
      if (this.learningDialog.currentPdfIndex < this.learningDialog.pdfUrls.length - 1) {
        this.learningDialog.currentPdfIndex++
      }
    },
    
    // 重新计算课程进度
    updateProgress() {
      const totalCount = this.totalLearning
      const completedCount = this.completedLearning
      this.course.progress = totalCount > 0 ? Math.round((completedCount / totalCount) * 100) : 0
    },
    getQuizButtonText(quiz) {
      return quiz.score !== null ? '查看结果' : '开始测验'
    },
    async handleQuizAction(quiz) {
      if (quiz.score !== null) {
        // 已完成的测验，获取结果详情
        await this.getQuizResult(quiz.id)
      } else {
        // 未完成的测验，跳转到测验页面
        this.$router.push({
          path: `/quiz/${quiz.id}`,
          query: {
            courseId: this.courseId
          }
        })
      }
    },
    
    // 获取测验结果
    async getQuizResult(paperId) {
      this.loading = true
      try {
        const res = await this.$api.exam.getPaperResult({
          course_id: this.courseId,
          paper_id: paperId
        })
        
        
        // 处理错题列表 - 只有真正答错的才显示
        const wrongQuestions = (res.wrong_questions || [])
          .filter(wq => {
            // 只显示学生答案和正确答案不一致的题目
            return wq.student_answer !== wq.correct_answer
          })
          .map(wq => {
            // 解析选项
            let options = []
            try {
              const parsedOptions = JSON.parse(wq.options || '[]')
              options = parsedOptions.map((opt, i) => {
                const match = opt.match(/^([A-Z])\.(.+)$/)
                if (match) {
                  return { key: match[1], text: match[2] }
                } else {
                  const key = String.fromCharCode(65 + i)
                  return { key, text: opt }
                }
              })
            } catch (e) {
            }
            
            return {
              id: wq.question_id,
              text: wq.question_content,
              options: options,
              userAnswer: wq.student_answer,
              correctAnswer: wq.correct_answer,
              explanation: wq.explanation || '暂无解析'
            }
          })
        
        
        // 更新弹窗数据
        this.quizResultDialog = {
          visible: true,
          score: res.score,
          totalQuestions: res.total_count,
          correctCount: res.correct_count,
          accuracy: res.total_count > 0 ? Math.round((res.correct_count / res.total_count) * 100) : 0,
          wrongQuestions: wrongQuestions
        }
      } catch (error) {
        this.$message.error('获取试卷结果失败')
      } finally {
        this.loading = false
      }
    },
    getOptionClass(option, question) {
      // 处理多选题：答案可能是 "A,B,C" 格式
      const correctAnswers = question.correctAnswer ? question.correctAnswer.split(',').map(a => a.trim()) : []
      const userAnswers = question.userAnswer ? question.userAnswer.split(',').map(a => a.trim()) : []
      
      const isCorrectAnswer = correctAnswers.includes(option.key)
      const isUserAnswer = userAnswers.includes(option.key)
      
      if (isCorrectAnswer && isUserAnswer) {
        // 用户选对了
        return 'correct-option'
      } else if (isCorrectAnswer && !isUserAnswer) {
        // 正确答案但用户没选
        return 'correct-option'
      } else if (!isCorrectAnswer && isUserAnswer) {
        // 用户选错了
        return 'wrong-option'
      }
      return ''
    },

    handleDownload(urlData) {
      // 解析 URL 数据，处理两种格式
      let urls = []
      
      try {
        // 如果是字符串，尝试解析
        if (typeof urlData === 'string') {
          const parsed = JSON.parse(urlData)
          
          if (Array.isArray(parsed)) {
            // 格式2: 直接是 URL 数组
            // ["http://xxx.pdf", "http://yyy.pdf"]
            parsed.forEach(item => {
              if (typeof item === 'string') {
                urls.push(item)
              } else if (item.file_urls) {
                // 格式1: [{file_urls: [...], file_urls_json: "..."}]
                urls.push(...item.file_urls)
              }
            })
          }
        } else if (Array.isArray(urlData)) {
          // 已经是数组
          urls = urlData
        }
      } catch (e) {
        this.$message.error('文件链接格式错误')
        return
      }
      
      if (urls.length === 0) {
        this.$message.warning('没有可下载的文件')
        return
      }
      
      if (urls.length === 1) {
        // 单个文件直接下载
        this.downloadFile(urls[0])
      } else {
        // 多个文件提示用户
        this.$confirm(`共有 ${urls.length} 个文件，是否在新窗口中打开所有文件？`, '提示', {
          confirmButtonText: '打开全部',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          urls.forEach((url, index) => {
            setTimeout(() => {
              this.downloadFile(url)
            }, index * 500)
          })
        }).catch(() => {
          this.$message.info('已取消')
        })
      }
    },
    
    downloadFile(url) {
      try {
        const fileName = url.split('/').pop() || 'download.pdf'
        
        // 直接在新窗口打开 URL，浏览器会自动处理下载
        // 如果服务器配置了 Content-Disposition: attachment，会触发下载
        // 否则会在新窗口预览
        const link = document.createElement('a')
        link.href = url
        link.target = '_blank'
        link.rel = 'noopener noreferrer'
        
        // 尝试设置 download 属性（同域名有效）
        link.download = fileName
        
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        
      } catch (error) {
        this.$message.error('打开文件失败')
      }
    }
  }
}
</script>

<style scoped>
.course-detail {
  padding: 20px 0;
}

.course-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 20px;
}

.header-left {
  flex: 1;
  min-width: 300px;
}

.title-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.course-title {
  font-size: 20px;
  font-weight: bold;
  color: #304156;
  margin: 0;
}

.course-meta {
  font-size: 13px;
  color: #86909C;
  margin: 0;
}

.header-right {
  width: 280px;
}

.progress-info {
  width: 100%;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  margin-bottom: 8px;
}

.progress-value {
  font-weight: 500;
  color: #165DFF;
}

.tabs-container {
  margin-bottom: 20px;
}

.tabs-header {
  display: flex;
  border-bottom: 2px solid #E5E6EB;
}

.tab-button {
  padding: 16px 32px;
  border: none;
  background: none;
  border-bottom: 2px solid transparent;
  margin-bottom: -2px;
  font-size: 14px;
  color: #86909C;
  cursor: pointer;
  transition: all 0.3s;
}

.tab-button.active {
  color: #165DFF;
  border-bottom-color: #165DFF;
  font-weight: 500;
}

.content-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: bold;
  color: #304156;
}

.section-title i {
  color: #165DFF;
  font-size: 18px;
}

.section-stats {
  font-size: 13px;
  color: #86909C;
}

.chapters-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.chapter-item {
  border: 1px solid #E5E6EB;
  border-radius: 8px;
  overflow: hidden;
}

.chapter-header {
  background-color: #F5F7FA;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s;
}

.chapter-header:hover {
  background-color: #E5E6EB;
}

.chapter-icon {
  transition: transform 0.3s;
  color: #86909C;
}

.chapter-icon.collapsed {
  transform: rotate(-90deg);
}

.chapter-content {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.learning-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  transition: background-color 0.3s;
}

.learning-item:hover {
  background-color: #F5F7FA;
}

.item-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
}

.item-icon i {
  font-size: 18px;
}

.item-info {
  flex: 1;
}

.item-title-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.item-title {
  font-size: 14px;
  color: #304156;
}

.item-meta {
  font-size: 13px;
  color: #86909C;
  margin: 0;
}

.quizzes-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.quiz-item {
  border: 1px solid #E5E6EB;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.quiz-info {
  flex: 1;
}

.quiz-title {
  font-size: 14px;
  font-weight: 500;
  color: #304156;
  margin-bottom: 4px;
}

.quiz-meta {
  font-size: 13px;
  color: #86909C;
  margin: 0;
}

.quiz-result {
  text-align: right;
  min-width: 80px;
}

.quiz-score {
  font-size: 16px;
  color: #86909C;
  display: block;
  margin-bottom: 4px;
}

.quiz-score.completed {
  color: #00B42A;
  font-weight: 500;
}

.quiz-status {
  font-size: 12px;
  color: #86909C;
  margin: 0;
}

.learning-content {
  padding: 20px 0;
}

.video-container,
.pdf-container,
.webpage-container {
  margin-bottom: 16px;
}

.learning-video {
  width: 100%;
  aspect-ratio: 16/9;
  border-radius: 8px;
  background-color: #000;
}

.pdf-viewer {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.pdf-pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  padding: 12px;
  background-color: #F5F7FA;
  border-radius: 8px;
}

.pdf-page-info {
  font-size: 14px;
  color: #304156;
  font-weight: 500;
  min-width: 60px;
  text-align: center;
}

.pdf-iframe {
  width: 100%;
  height: calc(100vh - 280px);
  min-height: 600px;
  max-height: 800px;
  border: 1px solid #E5E6EB;
  border-radius: 8px;
  background-color: #F5F7FA;
}

.pdf-iframe-multiple {
  height: calc(100vh - 320px);
  min-height: 500px;
  max-height: 750px;
}

.pdf-placeholder {
  aspect-ratio: 4/3;
  background-color: #F5F7FA;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.pdf-info {
  text-align: left;
}

.pdf-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #304156;
}

.pdf-download-btn {
  border-radius: 6px;
  padding: 10px 24px;
  font-size: 14px;
}

.pdf-download-btn:hover {
  opacity: 0.9;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(22, 93, 255, 0.3);
  transition: all 0.3s ease;
}

.learning-iframe {
  width: 100%;
  aspect-ratio: 16/9;
  border: 1px solid #E5E6EB;
  border-radius: 8px;
}

.content-desc {
  font-size: 14px;
  color: #606266;
  margin-top: 16px;
}

.quiz-result-content {
  padding: 20px 0;
}

.result-summary {
  text-align: center;
  margin-bottom: 24px;
}

.score-circle {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background-color: #E8F9F0;
  margin-bottom: 16px;
}

.score-number {
  font-size: 30px;
  font-weight: bold;
  color: #00B42A;
}

.score-unit {
  font-size: 14px;
  color: #00B42A;
  margin-left: 4px;
}

.result-message {
  font-size: 14px;
  color: #606266;
}

.result-stats {
  padding: 16px;
  background-color: #F5F7FA;
  border-radius: 8px;
  margin-bottom: 24px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.stat-row:last-child {
  margin-bottom: 0;
}

.stat-label {
  font-weight: 500;
  color: #304156;
}

.stat-value {
  color: #606266;
}

.wrong-questions {
  border: 1px solid #E5E6EB;
  border-radius: 8px;
  overflow: hidden;
}

.wrong-header {
  padding: 12px 16px;
  background-color: #F5F7FA;
  font-weight: 500;
  color: #304156;
}

.wrong-item {
  padding: 16px;
  border-bottom: 1px solid #E5E6EB;
}

.wrong-item:last-child {
  border-bottom: none;
}

.question-text {
  font-weight: 500;
  margin-bottom: 12px;
  color: #304156;
}

.options-list {
  margin: 0 0 16px 16px;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.option-key {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid #C9CDD4;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  flex-shrink: 0;
}

.option-item.wrong-option {
  color: #F53F3F;
}

.option-item.wrong-option .option-key {
  border-color: #F53F3F;
}

.option-item.correct-option {
  color: #00B42A;
}

.option-item.correct-option .option-key {
  border-color: #00B42A;
}

.answer-explanation {
  margin-top: 16px;
  padding: 12px;
  background-color: #F5F7FA;
  border-radius: 8px;
}

.explanation-title {
  font-size: 13px;
  font-weight: 500;
  margin-bottom: 4px;
  color: #304156;
}

.explanation-text {
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

/* 弹窗响应式样式 */
.learning-dialog >>> .el-dialog {
  margin: 5vh auto !important;
}

.quiz-result-dialog >>> .el-dialog {
  margin: 5vh auto !important;
}

@media (max-width: 1024px) {
  .learning-dialog >>> .el-dialog,
  .quiz-result-dialog >>> .el-dialog {
    margin: 3vh auto !important;
  }
}

@media (max-width: 768px) {
  .learning-dialog >>> .el-dialog__body,
  .quiz-result-dialog >>> .el-dialog__body {
    padding: 16px;
  }

  .learning-video,
  .learning-iframe {
    aspect-ratio: 16/9;
  }

  .pdf-iframe {
    height: calc(100vh - 200px);
    min-height: 400px;
    max-height: 600px;
  }

  .pdf-iframe-multiple {
    height: calc(100vh - 240px);
    min-height: 300px;
    max-height: 550px;
  }

  .score-circle {
    width: 80px;
    height: 80px;
  }

  .score-number {
    font-size: 28px;
  }

  .header-content {
    flex-direction: column;
  }

  .header-right {
    width: 100%;
  }

  .quiz-item {
    flex-wrap: wrap;
  }

  .quiz-result {
    order: -1;
    width: 100%;
    text-align: left;
  }
}
</style>